﻿using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Web;

using CashFlow.Db.DAL;
using CashFlow.Db.Entity;
using CashFlow.Web.Areas.SystemManage.Models.User.Result;

namespace CashFlow.Web.Areas.SystemManage.Service.Implement
{
    public class UserService
        : MyService<UserInfoEntity>, IUserService
    {
        public UserInfoModel QueryByPhone(string phone)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var entity = db.Queryable<UserInfoEntity>()
                               .Where(x => x.Phone == phone)
                               .Select(x => new UserInfoModel
                               {
                                   Id = x.Id,
                                   Name = x.Name,
                                   InvitationCode = x.InvitationCode,
                                   Phone = x.Phone
                               })
                               .First();
                return entity;
            }
        }

        public IList<UserInfoModel2> QueryShopUsersByShopManagerUserIdByWhere(
            int shopManagerUserId
            , string name
            , string phone)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var query = db.Queryable<UserInfoEntity>()
                              .InnerJoin<ShopUserEntity>((u, su) => u.Id == su.UserId)
                              .InnerJoin<UserInfoEntity>((u, su, u2) => u.ReferenceInvitationCode == u2.InvitationCode)
                              .Where((u, su, u2) => su.ShopManagerUserId == shopManagerUserId)
                              .OrderByDescending((u, su, u2) => u.CreateTime);

                if (!string.IsNullOrEmpty(name))
                {
                    query = query.Where((u, su, u2) => u.Name.Contains(name));
                }
                if (!string.IsNullOrEmpty(phone))
                {
                    query = query.Where((u, su, u2) => u.Phone.Contains(phone));
                }

                var ls = query.Select((u, su, u2) => new UserInfoModel2
                {
                    Id = u.Id,
                    Name = u.Name,
                    Phone = u.Phone,
                    InvitationCode = u.InvitationCode,
                    Reference = u2.Name,
                    ReferenceInvitationCode = u.ReferenceInvitationCode
                }).ToList();

                return ls;
            }
        }
    }
}